import { Context } from 'koa'
import menuService from '../services/menu'

export class MenuController {
  // 创建菜单
  async create(ctx: Context) {
    const menuData = ctx.request.body
    const menu = await menuService.create(menuData)
    ctx.status = 201
    ctx.body = {
      success: true,
      data: menu,
      message: '菜单创建成功'
    }
  }

  // 更新菜单
  async update(ctx: Context) {
    const { id } = ctx.params
    const updateData = ctx.request.body
    const menu = await menuService.update(parseInt(id), updateData)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: menu,
      message: '菜单更新成功'
    }
  }

  // 删除菜单
  async delete(ctx: Context) {
    const { id } = ctx.params
    await menuService.delete(parseInt(id))
    ctx.status = 200
    ctx.body = {
      success: true,
      message: '菜单删除成功'
    }
  }

  // 删除菜单及其所有子菜单
  async deleteWithChildren(ctx: Context) {
    try {
      const { id } = ctx.params
      await menuService.deleteWithChildren(parseInt(id))
      ctx.status = 200
      ctx.body = {
        success: true,
        message: '菜单及其子菜单删除成功'
      }
    } catch (error) {
      throw error
    }
  }

  // 查询单个菜单
  async findOne(ctx: Context) {
    const { id } = ctx.params
    const menu = await menuService.findOne(parseInt(id))
    ctx.status = 200
    ctx.body = {
      success: true,
      data: menu,
      message: '查询成功'
    }
  }

  // 查询所有菜单
  async findAll(ctx: Context) {
    const menus = await menuService.findAll(ctx.query)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: menus,
      message: '查询成功'
    }
  }

  // 根据父菜单ID查询子菜单
  async findByParentId(ctx: Context) {
    const { parentId } = ctx.params
    const parentIdNum = parentId === 'null' ? null : parseInt(parentId)
    const menus = await menuService.findByParentId(parentIdNum)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: menus,
      message: '查询成功'
    }
  }
}

export const menuController = new MenuController()
